<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>编辑商户经营产品</h2>
        <el-button type="info" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">

        <!-- 专属范围产品 -->
        <el-row v-for="item, index in dataForm.typeVillages" :key="item.type">
          <div style="font-size: 14px;color: #1e6abc;">
            范围类型 -> <el-tag size="mini" effect="dark" >{{formatVillageType(item.type)}}</el-tag>
          </div>

          <el-row v-for="item2, index2 in item.goodsVillageList" :key="item2.businessVillageId">
            <div style="margin-top: 20px;">
              <el-tag  effect="dark" >{{item2.village.name}}</el-tag>
            </div>

            <div class="tit">
              <h2>产品信息</h2>
              <div>
                <el-button plain type="danger" size="small" @click="handleDeleteGoods(item.type, index2, item2.businessVillageId)">一键删除</el-button>
                <el-button plain type="primary" size="small" @click="handleUpdateGoods(item.type, index2)">保 存</el-button>
                <el-button plain type="warning" size="small" @click="handleUpdateGoods(item.type, index2,2)">保存并上架</el-button>
                <el-button plain type="success" size="small" @click="handleOpenServers(item.type,index2,item2.businessVillageId)">货品库</el-button>
              </div>
            </div>
            <div style="width:calc(100vw - 300px);">
              <goods-change :business-id="dataForm.businessId" :goods-list="item2.goodsList"
                            @getGoodsList="getCompGoodsList">
              </goods-change>
            </div>
          </el-row>
        </el-row>

        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">全部保存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <!-- 从货品库选择产品进行复制 -->
    <business-server-select ref="businessServerSelect" :business-id="dataForm.businessId"
                            @getServerList="getCopyServerList"></business-server-select>

  </div>
</template>

<script>
  import * as message from "@/constants/message";
  import BusinessVillageApi from '@/api/business/businessVillage';
  import {getStorage} from '@/utils/auth'
  import {USER_INFO} from "@/constants/storeName"
  import UploadImg from "../../components/UploadImg.vue";
  import GoodsChange from "../../components/GoodsChange.vue";
  import BusinessServerSelect from "../../components/BusinessServerSelect.vue";

  export default {
    data() {
      return {
        userInfo: "",
        dataForm: {
          businessId: null,
          typeVillages: []
        },

        selectedParam: { // 选中货品库的参数
          type: "",
          index: ""
        },
        businessList: [],
        serverClassifyList: [],//二级服务分类列表
        serverClassify3List: [],//三级服务分类列表
        selectedServerList: [],//从serverLevel2List里面选择了服务分类之后形成新的服务分类列表
        loadingIns: false,
        roleRules: {}
      }
    },
    components: {
      UploadImg, GoodsChange, BusinessServerSelect
    },
    mounted() {
      this.init()
    },

    methods: {
      init() {
        // 获取用户的角色信息
        this.userInfo = getStorage(USER_INFO)
        // 当是进来的是商户的时候因为不能选择商户这个字段，所以校验规则需要做改变去掉商户校验
        /*if(this.userInfo.userRole == 3){
          this.$delete(this.roleRules,"businessId")
          this.$nextTick(()=>{
            // 调用nextTick生命周期函数避免
            this.$refs['dataForm'].resetFields();
          })
        }*/
        if (this.$route.query.id) {
          this.dataForm.businessId = this.$route.query.id
          this.getData()
        }
      },
      keydown(e) {
        if (e.keyCode == 32) {
          e.returnValue = false;
        }
      },
      getData() {
        BusinessVillageApi.listVillageAndGoods({
          businessId: this.dataForm.businessId
        }).then(res => {
          //console.log(res.data, 111111)
          if (!res.data){
            this.$message.warn("商户无经营范围，请先设置经营范围")
            return
          }
          //this.$Utils.bindingBean(this.dataForm, res.data)
          this.dataForm.typeVillages = res.data
          //console.log(this.dataForm.typeVillages, 565656)
          this.dataForm.typeVillages.forEach(a=>{
            if (!a.goodsVillageList) {
              a.goodsVillageList = []
            }else{
              a.goodsVillageList.forEach(b=>{
                if (!b.goodsList){
                  b.goodsList = []
                }
              })
            }
          })
          //console.log(this.dataForm, 222222)
        })
      },
      getCompGoodsList() {

      },
      formatVillageType(cellValue) {
        if (cellValue === 1) {
          return '专属'
        } else if (cellValue === 2) {
          return '小区'
        } else if (cellValue === 3) {
          return '公里数'
        } else if (cellValue === 4) {
          return '省市区'
        }
      },
      handleOpenServers(type, index,businessVillageId) {
        this.selectedParam.type = type;
        this.selectedParam.index = index;
        this.$refs.businessServerSelect.handleCreate(businessVillageId)
      },
      getCopyServerList(val) {
        let goods = val.map(a => {
          // 改变内存地址
          let good = JSON.parse(JSON.stringify(a))
          good.name = a.name
          good.introduce = a.introduce
          good.describes = a.describes
          good.images = a.images
          good.goodsCode = a.serverCode
          if (a.thirdClassifyId) {
            good.threeLevelClassList = [{id: a.thirdClassifyId, name: a.thirdClassifyName}]
          }
          return good
        })
        let type = this.selectedParam.type
        let index = this.selectedParam.index
        this.dataForm.typeVillages.forEach(vill=>{
          if (vill.type == type){
            vill.goodsVillageList[index].goodsList = vill.goodsVillageList[index].goodsList.concat(goods)
          }
        })

      },
      handleDeleteGoods(type,index,businessVillageId) {
        this.$confirm("该操作会清空当前经营范围选中的产品，并且删除当前经营范围的历史产品，是否继续？", message.TITLE_PROMPT, {})
          .then(() => {
            let params = {businessVillageId: businessVillageId}
            BusinessVillageApi.deleteVillageAndGoods(params).then(res => {
              this.$Utils.notifySuccess()
              this.dataForm.typeVillages.forEach(a=>{
                if (a.type == type){
                  a.goodsVillageList[index].goodsList = []
                }
              })
            })
          });
      },

      handleUpdateGoods(type, index,saleState) {
        let params = {}
        this.dataForm.typeVillages.forEach(a=>{
          if (a.type == type){
            params.businessVillageId = a.goodsVillageList[index].businessVillageId
            params.goodsList = a.goodsVillageList[index].goodsList
          }
        })

        if (!params.businessVillageId) {
          this.$message.error("请选中经营范围")
          return;
        }
        if (!params.goodsList || params.goodsList.length == 0) {
          this.$message.error("该经营范围下的产品不能为空")
          return;
        }

        if(saleState){
          params.saleState = saleState
        }
        BusinessVillageApi.updateVillageAndGoods(params).then(res => {
          this.$Utils.notifySuccess()
        })
      },
      sureClick() {

        /*this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
              .then(() => {
                if (this.dataForm.serverId){
                  this.editData();
                }else{
                  this.addData();
                }
            });
          }
        })*/
      },

      returnList() {
        this.$store.dispatch('delView', this.$route);
        this.$router.push({path: '/business/businessManagement'});
      }
    },

  }
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
<style lang="scss" scoped>
  .upload-img {
    &::v-deep .el-upload-dragger {
      display: flex;
      justify-content: space-around;
      align-items: center;

      .tip {
        padding-bottom: 30px;
      }
    }
  }
</style>
